package com.zryc.shop.ums.controller;

import com.zryc.shop.base.Result;
import com.zryc.shop.jwt.JWTUtil;
import com.zryc.shop.ums.entity.Admin;
import com.zryc.shop.ums.entity.Menu;
import com.zryc.shop.ums.entity.Role;
import com.zryc.shop.ums.service.IAdminService;
import com.zryc.shop.ums.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author zhaozhao
 * @since 2024-01-16
 */
@RestController
@Api(tags = "管理员信息接口列表")
@RequestMapping("/ums/admin")
public class AdminController {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/delete/{id}")
    @ApiOperation("删除管理员")
    public Result delete(@PathVariable @ApiParam(value = "管理员id", required = true) Long id) {
        return Result.ok(adminService.deleteAdminById(id));
    }

    @PostMapping("/register")
    @ApiOperation("创建管理员")
    public Result register(@RequestBody Admin admin) {
        adminService.save(admin);
        return Result.ok("创建成功");
    }

    @PostMapping("/updateStatus/{id}")
    @ApiOperation("更新管理员状态")
    public Result updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        adminService.updateAdminStatus(id, status);
        return Result.ok("更新成功");
    }

    @PostMapping("/update/{id}")
    @ApiOperation("更新管理员信息")
    public Result update(@PathVariable @ApiParam(value = "管理员id", required = true) Long id, @RequestBody Admin admin) {
        adminService.updateAdmin(id, admin);
        return Result.ok("更新成功");
    }

    @PostMapping("/updatePassword/{id}")
    @ApiOperation("修改管理员密码")
    public Result updatePassword(@PathVariable @ApiParam(value = "管理员id", required = true) Long id,
                                 @RequestParam @ApiParam(value = "旧密码", required = true) String oldPass,
                                 @RequestParam @ApiParam(value = "新密码", required = true) String newPass) {

        adminService.updateAdminPassword(id, oldPass, newPass);
        return Result.ok("密码修改成功");
    }

    @GetMapping("/list")
    @ApiOperation("分页查询管理员列表")
    public Result list(@RequestParam(required = false) @ApiParam(value = "姓名或账号") String keyword,
                       @RequestParam(defaultValue = "1") @ApiParam(value = "页码", required = true) Integer pageNum,
                       @RequestParam(defaultValue = "10") @ApiParam(value = "每页大小", required = true) Integer pageSize) {
        return Result.ok(adminService.list(keyword, pageNum, pageSize));
    }
    @PostMapping("/logout")
    @ApiOperation("管理员登出账号")
    public Result logout(@ApiIgnore HttpSession session){
        return Result.ok(adminService.logout(session));
    }


    //@RequestParam 不能接收json参数 改用@RequestBody
    @PostMapping("/login")
    @ApiOperation("管理员登录")
    public Result login(@RequestBody Admin admin) {
        Admin user = adminService.login(admin.getUsername(), admin.getPassword());
        if (user == null) {
            return Result.error(400, "用户名密码错误");
        } else {
            HashMap<String, String> data = new HashMap<>();
            String token = JWTUtil.create(3 * 60 * 60 * 1000, user.getId().toString(), user.getUsername(),user.getNickName());
            data.put("tokenType", "Bearer ");
            data.put("token", token);
            redisTemplate.opsForValue().set("token:"+user.getId(),token);
            return Result.ok(data);
        }
    }

    @GetMapping("/info")
    @ApiOperation("获取当前管理员信息")
    public Result info(@RequestHeader("Authorization") @ApiParam(value = "登录令牌", required = true) String token) {
        String userinfo = JWTUtil.parse(token.split(" ")[1]);
        Admin admin = adminService.getById(userinfo.split(",")[0]);
        String redisToken = (String) redisTemplate.opsForValue().get("token:" + admin.getId());
        if(redisToken.equals(token.split(" ")[1])){
            List<Role> roles = roleService.getRoleByAdminId(admin.getId());
            List<Menu> menus = adminService.getAllMenuByAdminId(admin.getId());
            admin.setMenus(menus);
            admin.setRoles(roles);
            return Result.ok(admin);
        }
        return Result.error(666,"权限不足");
    }

    @GetMapping("/{adminId}/roles")
    @ApiOperation("根据用户id查询角色列表")
    public Result getRoleByAdminId(@PathVariable @ApiParam(value = "管理员id", required = true) Long adminId) {
        Admin admin = adminService.getById(adminId);
        if (admin == null) {
            return Result.error(400000, "管理员不存在");
        }
        List<Role> roles = roleService.getRoleByAdminId(adminId);
        return Result.ok(roles);
    }

    @GetMapping("/{adminId}/menus}")
    @ApiOperation("根据用户id查询所有菜单列表")
    public Result getAllMenuByAdminId(@PathVariable @ApiParam(value = "管理员id", required = true) Long adminId) {
        Admin admin = adminService.getById(adminId);
        if (admin == null) {
            return Result.error(400000, "管理员不存在");
        }
        List<Menu> menus = adminService.getAllMenuByAdminId(adminId);
        return Result.ok(menus);
    }

    @GetMapping("/role/{adminId}")
    @ApiOperation("查询用户当前角色")
    public Result assignRole(@PathVariable @ApiParam(value = "管理员id", required = true) Long adminId){
        return Result.ok(roleService.getRoleByAdminId(adminId));
    }


    @PostMapping("/role/update")
    @ApiOperation("为当前用户分配角色")
    public Result update(@RequestParam Long adminId,@RequestParam List<Long> roleIds) {
        return Result.ok(roleService.updateRolesForAdmin(adminId,roleIds));
    }

}
